<?php

/**
 * Created by PhpStorm.
 * Author: GJX
 * Time: 2023/10/11 11:49
 * Desc:
 */
trait Trait_Api_Wallet
{

    public function wallet_order_log($order_info, $wallet)
    {
        $wallet_order_log = [
            'order_sn'       => $order_info['ordersn'],
            'amount'         => $wallet['amount'],
            'gift_amount'    => $wallet['gift_amount'],
            'gift_jifen'     => $wallet['gift_jifen'],
            'gift_coupon_id' => $wallet['gift_coupon_id'],
        ];

        $is_exist = DB::select()->from('wallet_order_log')
            ->where('order_sn', '=', $order_info['ordersn'])
            ->execute()->valid();
        if (!$is_exist) {
            DB::insert('wallet_order_log', array_keys($wallet_order_log))->values(array_values($wallet_order_log))->execute();
        }
    }

    public function product_deduction_handle($params)
    {
       $order = Model_Wallet_Order::product_deduction_handle($params);

        // 返回订单信息
        return $this->filter_data(array(
            'id',
            'orderid',
            'ordersn',
            'typeid',
            'status'
        ), $order);
    }

    public function wallet_details_list($params)
    {
        $offset = ($params['page'] - 1) * $params['pagesize'];
        $limit  = $params['pagesize'];

        $logModel = DB::select('id','order_sn','use_amount','describe','type','addtime','source')->from('wallet_log')
            ->where('member_id', '=', $params['mid']);
        switch ($params['filter_id']) {
            case 1:
                $logModel->and_where('type', '=', 1);
                break;
            case 2:
                $logModel->and_where('type', '=', 3);
                break;
            case 3:
                $logModel->and_where(DB::expr(" and type IN(2,4) "));
                break;
            case 4:
                $logModel->and_where('type','=', 5);
                break;
        }
        $total = $logModel->execute()->count();
        $logModel->order_by('addtime', 'DESC');
        $logModel->offset($offset)->limit($limit);
        $list = $logModel->execute()->as_array();

        foreach ($list as &$v){
            $v['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
            $v['type_name'] = Model_Wallet::$type_name[$v['type']];
            $v['source_name'] = Model_Wallet::$source_name[$v['source']];
            if($v['order_sn']){
                $product_order = DB::select()->from('member_order')->where('ordersn', '=', $v['order_sn'])->execute()->current();
                $v['orderid'] = $product_order['id'];
                $v['type_id'] = $product_order['typeid'];
            }
        }

        return [
            'list'    => $list,
            'total'   => ceil(bcdiv($total, $params['pagesize'], 1)),
        ];
    }
}